﻿using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Ekton_Manage_Framework.Methods
{
    public class SerializeHelper
    {
        private readonly Encryption _encryption;
        private readonly IHttpContextAccessor _accessor;
        public SerializeHelper(Encryption encryption,
                               IHttpContextAccessor accessor)
        {
            _encryption = encryption;
            _accessor = accessor;
        }

        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public static byte[] Serialize(object item)
        {
            var jsonString = JsonConvert.SerializeObject(item);

            return Encoding.UTF8.GetBytes(jsonString);
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static TEntity Deserialize<TEntity>(byte[] value)
        {
            if (value == null)
            {
                return default(TEntity);
            }
            var jsonString = Encoding.UTF8.GetString(value);
            return JsonConvert.DeserializeObject<TEntity>(jsonString);
        }

        public async Task<string> SerializeItem(object item)
        {
            return JsonConvert.SerializeObject(item);
        }

        public async Task<object> Deserialize(string item)
        {
            return JsonConvert.DeserializeObject<object>(item);
        }

        /// <summary>
        /// 解密并反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public async Task<T> Deserialize<T>()
        {
            var sign = _accessor.HttpContext.Request.Headers["SecretSign"].ToString().Trim();//获取请求头中的加密参数
            var realStr = _accessor.HttpContext.Request.Headers["result"].ToString().Trim();//获取请求头中的加密参数
            Console.WriteLine("sign=" + sign);
            var result = await _encryption.DecryptByAES(sign);//解密
            Console.WriteLine("result=" + result);
            return JsonConvert.DeserializeObject<T>(realStr);
        }

        public async Task<object> Deserialize(string item, object anonymous)
        {
            //dynamic deserializeData = await _serialize.DeserializeArray(result, anonymous);
            //var data = deserializeData.data.ToString();
            //var code = deserializeData.code.ToString();
            return JsonConvert.DeserializeAnonymousType(item, anonymous);
        }

        /// <summary>
        /// 解析Token
        /// </summary>
        /// <param name="jwtStr"></param>
        /// <returns></returns>
        public async Task<dynamic> SerializeJwt(string jwtStr)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
            object role;
            try
            {
                var userInfo = jwtToken.Claims.FirstOrDefault(t => t.Type.Equals("userInfo"))?.Value;
                dynamic deserializeData = await Deserialize(userInfo, null);
                var userId = deserializeData.userId.ToString();
                var userName = deserializeData.userName.ToString();
                var originalToken = jwtToken.Claims.FirstOrDefault(t => t.Type.Equals("originalToken"))?.Value;
                jwtToken.Payload.TryGetValue(ClaimTypes.Role, out role);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            dynamic tm = new
            {
                //Uid = (jwtToken.Id).ObjToInt(),
                //Role = role != null ? role.ObjToString() : "",
            };
            return tm;
        }
    }
}

